var app = getApp();
var shareTickets = ""
var id = ""
var shareid
var bannertimer
Page({
  /**
   * 页面的初始数据
   */
  data: {
    authbg: getApp().globalData.source + "red_packet/bg.png",
    authtitle: getApp().globalData.source + "red_packet/title1.png",
    authbtn2: getApp().globalData.source + "red_packet/btn2.png",
    authdialog: getApp().globalData.source + "dialog/dialog.png",
    ruleimg: getApp().globalData.source + 'ttbt_image_icon/rule.png',
    ruleshow: false,
    logins: true,
    sharebg: getApp().globalData.source + "ttbt_image_icon/img2.png",
    clickhide: false,
    imgindex: 0,
    imgreal: app.globalData.source + 'ttbt_image_icon/img4.png',
    imglist: [app.globalData.source + 'ttbt_image_icon/img4.png', app.globalData.source + 'ttbt_image_icon/img5.png', app.globalData.source + 'ttbt_image_icon/img6.png', app.globalData.source + 'ttbt_image_icon/img7.png'],
    animationData: {},
    first: false,
    showbottom: false,
    showloading: true,
    myshare: false,
    shareList: [],
    myshareList: [],
    maxPage: 10, //每页显示最大行数
    startPoint: 1, //第几页
    totalPages: 1, //总共几页
    mytotalPages: 1,
    bottomtext: '',
    page: 1,
    mypage: 1,
  },

  bindGetUserInfo: function(e) {
    getApp().authInfo(e);
  },
  freelisten: function(e) {
    var that = this
    var id = e.target.id
    var datas = {
      "userId": wx.getStorageSync("userId"),
      "programId": id,
      "shareSource": "0",
    }
    //调取保存用户分享的栏目
    console.log(JSON.stringify(datas))
    that.singleGroupId(datas);
  },
  /**
   * 跳转到分享明细页
   */
  shareDetailBindTap: function(e) {
    var id = e.currentTarget.dataset.id;
    var shareStatus = e.currentTarget.dataset.sharestatus
    var userIds = wx.getStorageSync("userId") //wx.getStorageSync("userId") 
    wx.navigateTo({
      url: "../../my/my_share/sharing_details/sharing_details?id=" + id + "&userIds=" + userIds + "&shareStatus=" + shareStatus + "&showhomeicon=fx",
      success: function() {},
      fail: function() {}
    })
  },


  nowTime: function() {
    var that = this;
    var dataList = that.data.myshareList
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    for (var i = 0; i < dataList.length; i++) {
      var createtime = dataList[i].shareCreateTime //创建时间 日期
      var endTime = dataList[i].survivalTime; //获取结束时间 小时
      endTime = createtime + endTime
      var day = 0,
        hour = 0,
        minute = 0,
        second = 0;
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        day = Math.floor(time / (60 * 60 * 24));
        hour = Math.floor(time / (60 * 60)) - (day * 24);
        minute = Math.floor(time / 60) - (day * 24 * 60) - (hour * 60);
        second = Math.floor(time) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
        if (hour <= 9) hour = '0' + hour;
        if (minute <= 9) minute = '0' + minute;
        if (second <= 9) second = '0' + second;
        dataList[i].survivalTime--;
        var str = hour + ':' + minute + ':' + second + " 结束"
        var shareStatus = dataList[i].shareStatus
        if (shareStatus == "0") {
          str = "成功"
        } else if (shareStatus == "2") {
          str = "失败"
        }
      } else {
        var str = "已结束";
        var shareStatus = dataList[i].shareStatus
        if (shareStatus == "0") {
          str = "成功"
        } else if (shareStatus == "1") {
          str = "进行中";
        } else if (shareStatus == "2") {
          str = "失败"
        }
        //clearInterval(nowTime);
      }
      dataList[i].timers = str; //将timers时间字段放入数组中  
    }

    that.setData({
      myshareList: dataList //重新赋值供页面获取
    })
    setTimeout(that.nowTime, 1000);

  },

  /**
   * 我的分享
   */
  getmyshare: function() {
    var vm = this
    vm.setData({
      logins: true,
    })
    var data = {
      "startPoint": vm.data.mypage,
      "maxPage": 10
    }
    //我的分享列表
    getApp().request(getApp().globalData.https + "programResource/myProgramShare/" + wx.getStorageSync("userId"),
      "get", data,
      function(res) {
        console.log(res)
        wx.stopPullDownRefresh()
        if (res.code == 0) {
          vm.nowTime(res.data.data)
          if(vm.data.mypage==1){
            vm.setData({
              myshareList: [],
            })
          }
          vm.setData({
            myshareList: vm.data.myshareList.concat(res.data.data),
            mytotalPages: res.data.totalPages,
            showloading: false,
          })
        } else if (res.code == "016") {
          vm.setData({
            bottomtext: '还没有分享哦.',
            showloading: false
          })
        }
      },
      function(res) {
        console.log(res)
      })
  },

  // 跳转详情页TODO。。。。暂时封印
  todetails: function(event) {
    var vm = this
    var id = event.currentTarget.dataset.id;
    var index = event.currentTarget.dataset.index;
    if (vm.data.myshareList[index].useH5 == undefined) {
      wx.navigateTo({
        url: '../details/details?id=' + id + "&season=" + 1 + "&url=" + undefined,
      })
      return
    }
    if (vm.data.myshareList[index].useH5 == 0) {
      wx.navigateTo({
        url: '../details/details?id=' + id + "&season=" + 1 + "&url=" + vm.data.myshareList[index].h5Url,
      })
    } else {
      wx.navigateTo({
        url: '../details/details?id=' + id + "&season=" + 1 + "&url=" + undefined,
      })
    }
  },

  todetails2: function(event) {
    var vm = this
    var id = event.currentTarget.dataset.id;
    var index = event.currentTarget.dataset.index;

    if (vm.data.shareList[index].useH5 == 0) {
      wx.navigateTo({
        url: '../details/details? id=' + id + "&season=" + 1 + "&url=" + vm.data.shareList[index].h5Url,
      })
    } else {
      wx.navigateTo({
        url: '../details/details?id=' + id + "&season=" + 1 + "&url=" + undefined,
      })
    }
  },

  /**
   * 分享免费听列表
   */
  getsharelist: function() {
    var vm = this
    vm.setData({
      logins: true,
    })
    var data = {
      "startPoint": vm.data.page,
      "maxPage": vm.data.maxPage
    }
    getApp().request(getApp().globalData.https + "programResource/programShare",
      "get", data,
      function(res) {
        wx.stopPullDownRefresh()
        console.log(res)
        if (res.code == 0) {
          if (res.data.data.length > 0) {
            // 获取系统信息  
            vm.setData({
              shareList: vm.data.shareList.concat(res.data.data),
              totalPages: res.data.totalPages,
              showloading: false,
            });
          }
        } else if (res.code == "016") {
          vm.setData({
            bottomtext: '暂无数据.',
            showloading: false
          })
          //   wx.showToast({
          //     title: res.message,
          //     icon: 'none',
          //     duration: 2000
          //   })
        }
      },
      function(res) {
        console.log(res)
      });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var vm = this
    vm.setData({
      logins: true,
    })
    //this.getsharelist();
    //this.getmyshare()
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out',
    })

    this.animation = animation
    //点击图标 切换效果 ，通过动态改变两张图片的显隐性
    var inter = setInterval(function() {
      vm.setData({
        clickhide: !vm.data.clickhide,
      })
    }, 250)

    //切换banner  右侧图片
    bannertimer = setInterval(function() {
      if (vm.data.imgindex == 3) {
        vm.setData({
          imgindex: 0
        })
        vm.setData({
          imgreal: vm.data.imglist[vm.data.imgindex]
        })
      } else {
        vm.setData({
          imgindex: vm.data.imgindex + 1
        })
        vm.setData({
          imgreal: vm.data.imglist[vm.data.imgindex]
        })
      }

      animation.opacity(0.1)
      animation.scale(0, 0).step({
        duration: 100,
      })
      animation.opacity(1)
      animation.scale(1, 1).step()
      vm.setData({
        animationData: animation.export(),
      })
    }, 4000)

    if (options.right) {
      this.setData({
        myshare: true,
      })
    }
  },
  changeitem: function() {
    var vm = this
    this.setData({
      page: 1,
      shareList: [],
      myshare: false,
      bottomtext: "",
      showloading: true
    })
    vm.getsharelist();
  },

  changeitem2: function() {
    var vm = this
    this.setData({
      mypage: 1,
      myshareList: [],
      myshare: true,
      bottomtext: "",
      showloading: true
    })
    this.getmyshare()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.myshare) {
      this.setData({
        mypage: 1,
        myshareList: []
      })
      this.getmyshare();
    } else {
      this.setData({
        page: 1,
        shareList: []
      })
      this.getsharelist();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    // clearInterval(bannertimer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    if (this.data.myshare) {
      this.setData({
        mypage: 1,
        mysharelist: [],
        showbottom: false,
      })
      this.getmyshare();
    } else {
      this.setData({
        page: 1,
        shareList: []
      })
      this.getsharelist();
    }

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var vm = this;
    if (this.data.myshare) {
      if (vm.data.mypage < vm.data.mytotalPages) {
        vm.setData({
          mypage: vm.data.mypage + 1,
          showbottom: true,
          bottomtext: '正在加载中...'
        })
        vm.getmyshare()
      } else {
        vm.setData({
          showbottom: true,
          bottomtext: '没有更多内容了'
        })
      }
    } else {
      if (vm.data.page < vm.data.totalPages) {
        vm.setData({
          page: vm.data.page + 1,
          showbottom: true,
          bottomtext: '正在加载中...'
        })
        vm.getsharelist()
      } else {
        vm.setData({
          showbottom: true,
          bottomtext: '没有更多内容了'
        })
        // wx.showToast({
        //   title: '没有更多数据了',
        //   icon: 'none',
        //   duration: 2000
        // })
      }
    }


  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    var that = this
    var id = e.target.id
    var userIds = wx.getStorageSync("userId")
    var datas = {
      "userId": userIds,
      "programId": id,
      "shareSource": "0",
    }
    console.log(JSON.stringify(datas))
    //调取保存用户分享的栏目
    that.singleGroupId(datas);
    var imageUrl = getApp().globalData.shareurl
    var title = e.target.dataset.title
    var data = {
      programId: id,
      title: title,
      imageUrl: imageUrl,
      path: "/pages/my/my_share/sharing_details/sharing_details"
    }
    var vm = this

    return {
      title: wx.getStorageSync("userInfo").nickName + '邀您一起听' + title,
      path: data.path + "?userIds=" + userIds + "&id=" + id + "&showhomeicon=fx",
      imageUrl: data.imageUrl,
      success(res) {},
      fail(e) {
        console.log("fail")
      },
      //分享完成
      complete() {
        console.log("complete")
      }
    }
  },
  /**
   * 个人用户分享保存服务器方法调用
   */
  singleGroupId: function(data) {
    console.log("个人分享。。。。。。")
    app.request(app.globalData.https + "programResource/myProgramShare", //处理获取分享群信息
      "post", data,
      function(res) {
        if (res.code == 0) {
          console.log("调用接口" + res)
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },
  ruleShow: function() {
    var that = this
    this.setData({
      ruleshow: !that.data.ruleshow
    })

  },
  ruleHide: function() {
    var that = this
    this.setData({
      ruleshow: !that.data.ruleshow
    })

  },
})